import * as Cesium from 'cesium';

/**
 * 卫星云图工具类，用于处理卫星云图数据和绘制卫星云图
 */
export class SatelliteCloudUtils {
  constructor(viewer) {
    this.viewer = viewer;
    this.satelliteLayer = null; // 卫星云图图层
    this.satelliteData = null; // 卫星云图数据
    this.timePoints = []; // 时间轴数据
    this.currentIndex = 0; // 当前时间点索引
    this.animationTimer = null; // 动画定时器
    this.isPlaying = false; // 播放状态
    this.playbackSpeed = 1000; // 播放速度（毫秒/帧）
    this.opacity = 0.8; // 默认透明度
    this.baseUrl = 'https://gswarn.weather.com.cn/app/api/cn_scw_radar_cloud?type=satellite'; // 卫星云图接口
    this.imageCache = new Map(); // 图片缓存
    this.isPreloading = false; // 预加载状态
    this.preloadPromise = null; // 预加载Promise
    this.isLayerVisible = false; // 图层显示状态
    this.onFrame = null; // 可选回调：(index, timePoint) => void
  }

  /**
   * 从接口获取卫星云图数据
   * @returns {Promise<Object>} 卫星云图数据
   */
  async fetchSatelliteData() {
    try {
      const response = await fetch(this.baseUrl);
      const data = await response.json();
      return data;
    } catch (error) {
      console.error('获取卫星云图数据失败:', error);
      throw error;
    }
  }

  /**
   * 解析卫星云图数据
   * @param {Object} data - 卫星云图数据
   * @returns {Object} 解析后的卫星云图数据
   */
  parseSatelliteData(data) {
    if (!data || !data.l || !data.l.length) {
      throw new Error('无效的卫星云图数据');
    }
    
    // 解析时间轴和图片URL
    const timePoints = data.l.map(item => ({
      time: item.l1,
      url: item.l2.trim() // 去除URL前后的空格
    }));
    
    // 按时间排序
    timePoints.sort((a, b) => new Date(a.time) - new Date(b.time));
    
    this.satelliteData = data;
    this.timePoints = timePoints;
    this.currentIndex = 0;
    
    return {
      timePoints,
      totalFrames: timePoints.length
    };
  }

  /**
   * 创建卫星云图图层
   * @returns {Cesium.ImageryLayer} 卫星云图图层
   */
  createSatelliteLayer() {
    if (!this.timePoints.length) {
      throw new Error('没有可用的卫星云图数据');
    }
    
    // 使用数据中的rect字段作为卫星云图范围，默认使用中国区域范围
    let rectangle = Cesium.Rectangle.fromDegrees(70, 15, 140, 55); // 默认中国区域范围
    
    if (this.satelliteData && this.satelliteData.rect && this.satelliteData.rect.length === 4) {
      // rect格式：[minLat, maxLat, minLng, maxLng] 或 [minLng, minLat, maxLng, maxLat]，需要根据实际数据调整
      // 假设rect格式为：[minLat, maxLat, minLng, maxLng]
      const [minLat, maxLat, minLng, maxLng] = this.satelliteData.rect.map(parseFloat);
      rectangle = Cesium.Rectangle.fromDegrees(minLng, minLat, maxLng, maxLat);
    }
    
    // 使用 SingleTileImageryProvider 将单张图片映射到指定矩形，避免被当作模板平铺
    // 为兼容某些 Cesium 扩展/检查，显式提供 tileWidth/tileHeight（优先使用缓存的实际图片尺寸）
    const firstUrl = this.timePoints[0].url;
    const cachedImg = this.imageCache.get(firstUrl);
    const defaultTileSize = 2048;
    const imageryOptions = {
      url: firstUrl,
      rectangle: rectangle,
      tileWidth: cachedImg ? cachedImg.width : defaultTileSize,
      tileHeight: cachedImg ? cachedImg.height : defaultTileSize
    };

    const imageryProvider = new Cesium.SingleTileImageryProvider(imageryOptions);

    // 添加图层到 viewer
    this.satelliteLayer = this.viewer.imageryLayers.addImageryProvider(imageryProvider);
    this.satelliteLayer.alpha = this.opacity;
    // 根据保存的显示状态设置初始图层的显示状态
    this.satelliteLayer.show = this.isLayerVisible;

    // 如果外部注册了帧回调，调用一次以同步初始状态
    if (typeof this.onFrame === 'function') {
      this.onFrame(this.currentIndex, this.getCurrentTimePoint());
    }
    
    return this.satelliteLayer;
  }

  /**
   * 预加载单个图片
   * @param {string} url - 图片URL
   * @returns {Promise<Image>} 加载完成的图片
   */
  preloadImage(url) {
    if (this.imageCache.has(url)) {
      return Promise.resolve(this.imageCache.get(url));
}
    
    return new Promise((resolve, reject) => {
  const img = new Image();
      img.crossOrigin = 'anonymous';
      img.onload = () => {
        this.imageCache.set(url, img);
        resolve(img);
      };
      img.onerror = (error) => {
        console.error(`预加载图片失败: ${url}`, error);
        reject(error);
      };
      img.src = url;
    });
  }
  
  /**
   * 预加载所有图片
   * @returns {Promise<void>} 预加载完成的Promise
   */
  async preloadAllImages() {
    if (this.isPreloading || this.preloadPromise) {
      return this.preloadPromise;
    }
    
    this.isPreloading = true;
    
    this.preloadPromise = Promise.all(
      this.timePoints.map(point => 
        this.preloadImage(point.url).catch(() => {
          // 忽略单个图片加载失败，继续加载其他图片
          return null;
        })
      )
    ).finally(() => {
      this.isPreloading = false;
      this.preloadPromise = null;
    });
    
    return this.preloadPromise;
  }
  
  /**
   * 更新卫星云图图片
   * @param {number} index - 时间点索引
   */
  updateSatelliteImage(index) {
    if (!this.timePoints.length) {
      return;
    }
    
    // 确保索引在有效范围内
    this.currentIndex = Math.max(0, Math.min(index, this.timePoints.length - 1));
    
    const currentTimePoint = this.timePoints[this.currentIndex];
    
    // 使用数据中的rect字段作为卫星云图范围，默认使用中国区域范围
    let rectangle = Cesium.Rectangle.fromDegrees(70, 15, 140, 55); // 默认中国区域范围
    
    if (this.satelliteData && this.satelliteData.rect && this.satelliteData.rect.length === 4) {
      // rect格式：[minLat, maxLat, minLng, maxLng] 或 [minLng, minLat, maxLng, maxLat]，需要根据实际数据调整
      // 根据实际数据，rect格式为：[minLat, maxLat, minLng, maxLng]
      const [minLat, maxLat, minLng, maxLng] = this.satelliteData.rect.map(parseFloat);
      rectangle = Cesium.Rectangle.fromDegrees(minLng, minLat, maxLng, maxLat);
    }
    
    // 移除旧的图层
    if (this.satelliteLayer) {
      this.viewer.imageryLayers.remove(this.satelliteLayer);
      this.satelliteLayer = null;
    }
    
    // 创建新的图层，单张图片映射到指定矩形
    // 为兼容某些 Cesium 扩展/检查，显式提供 tileWidth/tileHeight（优先使用缓存的实际图片尺寸）
    const curUrl = currentTimePoint.url;
    const cachedCurImg = this.imageCache.get(curUrl);
    const defaultTileSize = 2048;
    const imageryOptions = {
      url: curUrl,
      rectangle: rectangle,
      tileWidth: cachedCurImg ? cachedCurImg.width : defaultTileSize,
      tileHeight: cachedCurImg ? cachedCurImg.height : defaultTileSize
    };

    const imageryProvider = new Cesium.SingleTileImageryProvider(imageryOptions);

    // 添加新图层到 viewer
    this.satelliteLayer = this.viewer.imageryLayers.addImageryProvider(imageryProvider);
    this.satelliteLayer.alpha = this.opacity;
    // 根据保存的显示状态设置新图层的显示状态
    this.satelliteLayer.show = this.isLayerVisible;
    // 通知外部当前帧已改变
    if (typeof this.onFrame === 'function') {
      this.onFrame(this.currentIndex, this.getCurrentTimePoint());
    }
    
    return currentTimePoint;
  }
  
  /**
   * 开始动画播放
   */
  playAnimation() {
    if (this.isPlaying || !this.timePoints.length) {
      return;
    }
    
    this.isPlaying = true;
    this.animate();
  }
  
  /**
   * 动画循环
   */
  animate() {
    if (!this.isPlaying) {
      return;
    }
    
    // 更新到下一个时间点
    this.currentIndex++;
    
    // 如果到达最后一个点，重置索引
    if (this.currentIndex >= this.timePoints.length) {
      this.currentIndex = 0;
    }
    
    // 更新卫星云图
    this.updateSatelliteImage(this.currentIndex);

    // 调用外部回调以通知当前索引变化（供 UI 同步）
    if (typeof this.onFrame === 'function') {
      this.onFrame(this.currentIndex, this.getCurrentTimePoint());
    }
    
    // 设置下一次动画
    this.animationTimer = setTimeout(() => {
      this.animate();
    }, this.playbackSpeed);
  }
  
  /**
   * 暂停动画播放
   */
  pauseAnimation() {
    this.isPlaying = false;
    if (this.animationTimer) {
      clearTimeout(this.animationTimer);
      this.animationTimer = null;
    }
  }
  
  /**
   * 停止动画播放
   */
  stopAnimation() {
    this.pauseAnimation();
    this.currentIndex = 0;
    this.updateSatelliteImage(this.currentIndex);
  }
  
  /**
   * 设置图层透明度
   * @param {number} opacity - 透明度（0-1）
   */
  setOpacity(opacity) {
    this.opacity = Math.max(0, Math.min(opacity, 1));
    if (this.satelliteLayer) {
      this.satelliteLayer.alpha = this.opacity;
    }
  }
  
  /**
   * 显示图层
   */
  showLayer() {
    this.isLayerVisible = true;
    if (this.satelliteLayer) {
      this.satelliteLayer.show = true;
    }
  }
  
  /**
   * 隐藏图层
   */
  hideLayer() {
    this.isLayerVisible = false;
    if (this.satelliteLayer) {
      this.satelliteLayer.show = false;
    }
  }
  
  /**
   * 销毁资源
   */
  destroy() {
    this.pauseAnimation();
    
    if (this.satelliteLayer) {
      this.viewer.imageryLayers.remove(this.satelliteLayer);
      this.satelliteLayer = null;
    }
    
    this.satelliteData = null;
    this.timePoints = [];
    this.currentIndex = 0;
  }
  
  /**
   * 获取当前时间点
   * @returns {Object} 当前时间点数据
   */
  getCurrentTimePoint() {
    if (!this.timePoints.length) {
      return null;
    }
    return this.timePoints[this.currentIndex];
  }
  
  /**
   * 获取总帧数
   * @returns {number} 总帧数
   */
  getTotalFrames() {
    return this.timePoints.length;
  }
  
  /**
   * 设置播放速度
   * @param {number} speed - 播放速度（毫秒/帧）
   */
  setPlaybackSpeed(speed) {
    this.playbackSpeed = speed;
  }
  
  /**
   * 快进
   */
  fastForward() {
    if (!this.timePoints.length) {
      return;
    }
    
    this.currentIndex = Math.min(this.currentIndex + 5, this.timePoints.length - 1);
    this.updateSatelliteImage(this.currentIndex);
  }
  
  /**
   * 快退
   */
  rewind() {
    if (!this.timePoints.length) {
      return;
    }
    
    this.currentIndex = Math.max(this.currentIndex - 5, 0);
    this.updateSatelliteImage(this.currentIndex);
  }
}